#include "binarystream.h"

#include <iostream>

BinaryStream::BinaryStream(std::fstream& fileStream, u_int32_t size, bool illimited) : fileStream(fileStream) {
    this->size = size;
    this->illimited = illimited;
    this->pos = 0;
    this->buffer = size > 0 ? new byte[size] : nullptr;
}

BinaryStream::~BinaryStream() {
    if (buffer)
        delete [] buffer;
}

void BinaryStream::checkPosition(bool reading, u_int32_t sizeData) {
    if (size == 0 || pos + sizeData <= size)
        return;
    if (pos + sizeData > size && ! illimited)
        throw -1;

    pos = 0;
    if (reading)
        load();
    else
        flush();
}

void BinaryStream::load(){
    fileStream.read((char*) buffer, size);
}

void BinaryStream::flush(){
    fileStream.write((char*) buffer, size);
    fileStream.flush();
}

std::string BinaryStream::readString(){
    u_int16_t length = readPrimitive<u_int16_t>();
    std::string str;

    checkPosition(true, length);
    if (buffer)
        str.assign((char*) &buffer[pos], length);
    pos += length;
    return str;
}

void BinaryStream::writeString(std::string const str){
    writePrimitive<u_int16_t>(str.length());
    checkPosition(false, str.length());
    if (buffer)
        str.copy((char*) &buffer[pos], str.length(), 0);
    pos += str.length();

}
